/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ventanas;

import datos.Cliente;
import java.awt.event.KeyEvent;
import java.beans.PropertyVetoException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.tool.stat.BeanTableModel;
import tools.HibernateUtil;
import tools.ListTableModel;

/**
 *
 * @author crey
 */
public class FrmCliente extends javax.swing.JInternalFrame {

    /**
     * Creates new form FrmCliente
     */
    private String query_all_clients = "from Cliente";
    private String query_client_selected = "select c.cedula, c.nombre,c.email, c.fechaCompra from Cliente c where c.id = ";
    private List resultList;
    private int ACCION;//NUEVO = 1, MODIFICAR = 2, BORRAR = 0

    public FrmCliente() {
        try {
            initComponents();
            this.setSelected(true);
            this.btn_save.setEnabled(false);
            this.mnu_newClient.setEnabled(true);
            this.ACCION = 2;
            executeHQLQuery(query_all_clients);
            if (this.resultList.size() > 0) {
                upLoadDate(0);
            }
        } catch (PropertyVetoException ex) {
            Logger.getLogger(FrmCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void executeHQLQuery(String hql) {
        try {
            Session session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            Query q = session.createQuery(hql);
            resultList = q.list();
            displayResult(resultList);
            session.getTransaction().commit();
        } catch (HibernateException he) {
            he.printStackTrace();
        }
    }

    private void displayResult(List resultList) {
        LinkedList<String> tableHeaders = new LinkedList<String>();
        LinkedList tableData = new LinkedList();
        tableHeaders.add("Cedula");
        tableHeaders.add("Nombre");
        tableHeaders.add("Apellido");
        tableHeaders.add("Ultima_Compra");
        ListTableModel model = new ListTableModel(tableHeaders);
        for (Object o : resultList) {
            Cliente cli = (Cliente) o;
            LinkedList<Object> oneRow = new LinkedList<Object>();
            oneRow.add(cli.getCedula());
            oneRow.add(cli.getNombre());
            oneRow.add(cli.getApellido());
            SimpleDateFormat sdf = new SimpleDateFormat();
            String fecha = sdf.format(cli.getFechaCompra());
            oneRow.add(fecha);
            tableData.add(oneRow);
            model.addRow(oneRow);
        }


        this.tabla_clientes.setModel(model);
    }

    private void upLoadDate(int row) {
        Cliente cli = (Cliente) this.resultList.get(row);
        int cedula = cli.getCedula().intValue();
        this.txt_cedula.setText(Integer.toString(cedula));
        this.txt_nombre.setText(cli.getNombre());
        this.txt_apellido.setText(cli.getApellido());
        this.txt_mail.setText(cli.getEmail());
        SimpleDateFormat sdf = new SimpleDateFormat();
        String fecha = sdf.format(cli.getFechaUpdate());
        this.txt_lastUpdate.setText(fecha);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txt_cedula = new javax.swing.JTextField();
        txt_nombre = new javax.swing.JTextField();
        txt_apellido = new javax.swing.JTextField();
        txt_mail = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txt_lastUpdate = new javax.swing.JLabel();
        btn_edit = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabla_clientes = new javax.swing.JTable();
        btn_save = new javax.swing.JButton();
        btn_newClient = new javax.swing.JButton();
        btn_cerrar = new javax.swing.JButton();
        btn_borrar = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        mnu_newClient = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        jMenuItem2 = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        mnuCerrar = new javax.swing.JMenuItem();

        setClosable(true);
        setTitle("ABM [Clientes]");
        setToolTipText("ABM-Cliente");
        setFocusTraversalPolicyProvider(true);
        setFrameIcon(null);
        setInheritsPopupMenu(true);
        setNextFocusableComponent(btn_edit);
        try {
            setSelected(true);
        } catch (java.beans.PropertyVetoException e1) {
            e1.printStackTrace();
        }
        setVisible(true);
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                newClientKeyPress(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Cedula de Identificación");

        jLabel2.setText("Nombres");

        jLabel3.setText("Apellidos");

        jLabel4.setText("Correo Electronico");

        txt_cedula.setEditable(false);

        txt_nombre.setEditable(false);

        txt_apellido.setEditable(false);

        txt_mail.setEditable(false);

        jLabel5.setText("Last Update");

        txt_lastUpdate.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        txt_lastUpdate.setText("DD/MM/AAAA");

        btn_edit.setText("Modificar");
        btn_edit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_editActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txt_cedula, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
                    .addComponent(txt_nombre)
                    .addComponent(txt_apellido)
                    .addComponent(txt_mail))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txt_lastUpdate, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btn_edit)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txt_cedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(txt_lastUpdate))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txt_nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(txt_apellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(txt_mail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btn_edit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(2, 2, 2)))
                .addContainerGap())
        );

        tabla_clientes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Nombre", "Email", "Ultima Venta"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabla_clientes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabla_clientesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabla_clientes);

        btn_save.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        btn_save.setText("Guardar Cambios");
        btn_save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_saveActionPerformed(evt);
            }
        });

        btn_newClient.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        btn_newClient.setText("Nuevo Cliente");
        btn_newClient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_newClientActionPerformed(evt);
            }
        });

        btn_cerrar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        btn_cerrar.setText("Cerrar Ventana");
        btn_cerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_cerrarActionPerformed(evt);
            }
        });

        btn_borrar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        btn_borrar.setText("Borrar Cliente");
        btn_borrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_borrarActionPerformed(evt);
            }
        });

        jMenu1.setText("Operaciones");

        mnu_newClient.setText("Crear nuevo Cliente");
        mnu_newClient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnu_newClientActionPerformed(evt);
            }
        });
        jMenu1.add(mnu_newClient);
        jMenu1.add(jSeparator1);

        jMenuItem2.setText("Buscar Cliente");
        jMenu1.add(jMenuItem2);
        jMenu1.add(jSeparator2);

        mnuCerrar.setText("Cerrar");
        mnuCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuCerrarActionPerformed(evt);
            }
        });
        jMenu1.add(mnuCerrar);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btn_newClient, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btn_save, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btn_cerrar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btn_borrar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btn_newClient, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btn_save, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(3, 3, 3)
                        .addComponent(btn_borrar, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btn_cerrar, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-814)/2, (screenSize.height-401)/2, 814, 401);
    }// </editor-fold>//GEN-END:initComponents

    private void mnuCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuCerrarActionPerformed
        this.dispose();
    }//GEN-LAST:event_mnuCerrarActionPerformed

    private void tabla_clientesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabla_clientesMouseClicked
        upLoadDate(this.tabla_clientes.getSelectedRow());
    }//GEN-LAST:event_tabla_clientesMouseClicked

    private void btn_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_saveActionPerformed
        this.btn_save.setEnabled(false);
        this.mnu_newClient.setEnabled(true);
        this.btn_newClient.setEnabled(true);
        if (this.ACCION == 1) {
            Cliente c = new Cliente();
            c.setCedula(new BigDecimal(Integer.parseInt(this.txt_cedula.getText())));
            c.setApellido(this.txt_apellido.getText());
            c.setNombre(this.txt_nombre.getText());
            c.setEmail(this.txt_mail.getText());
            c.setFechaUpdate(new Date());
            c.setFechaCompra(new Date());
            saveData(c);
        }
        this.ACCION = 2;
    }//GEN-LAST:event_btn_saveActionPerformed

    private boolean saveData(Cliente c) {
        this.resultList.add(c);
        try {
            Session session = HibernateUtil.getSessionFactory().openSession();//OJO -2
            session.beginTransaction();     //OJO -1   
            session.save(c);//OJO
            displayResult(resultList);//OJO2
            session.getTransaction().commit();//OJO ok
        } catch (HibernateException he) {
            he.printStackTrace();
        }
        return true;
    }
    
    private boolean deleteData(Cliente c)///NO FUNCIONA !!! OJO!!!
    {
         
        try {
            Session session = HibernateUtil.getSessionFactory().openSession();//OJO -2
            session.beginTransaction();     //OJO -1   
            session.delete(c);
            this.resultList.remove(c);
            //session.save(c);//OJO
            displayResult(resultList);//OJO2
            session.getTransaction().commit();//OJO ok
        } catch (HibernateException he) {
            he.printStackTrace();
        }   
        return true;
    }     

    private void btn_editActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_editActionPerformed
        this.btn_save.setEnabled(true);
        this.mnu_newClient.setEnabled(false);
        this.txt_apellido.setEditable(true);
        this.txt_cedula.setEditable(true);
        this.txt_mail.setEditable(true);
        this.txt_nombre.setEditable(true);
        this.ACCION = 2;

    }//GEN-LAST:event_btn_editActionPerformed

    private void mnu_newClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnu_newClientActionPerformed
        this.btn_save.setEnabled(true);
        this.mnu_newClient.setEnabled(false);
        this.btn_edit.setEnabled(false);
        this.ACCION = 1;
        this.txt_apellido.setEditable(true);
        this.txt_cedula.setEditable(true);
        this.txt_mail.setEditable(true);
        this.txt_nombre.setEditable(true);
        this.txt_apellido.setText("");
        this.txt_cedula.setText("");
        this.txt_mail.setText("");
        this.txt_nombre.setText("");
    }//GEN-LAST:event_mnu_newClientActionPerformed

    private void btn_newClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_newClientActionPerformed
        this.btn_newClient.setEnabled(false);
        this.mnu_newClientActionPerformed(null);
        
    }//GEN-LAST:event_btn_newClientActionPerformed

    private void newClientKeyPress(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_newClientKeyPress
        if(Integer.parseInt(Long.toString(evt.getKeyCode())) == KeyEvent.VK_F1)
        {
            mnu_newClientActionPerformed(null);
        }
    }//GEN-LAST:event_newClientKeyPress

    private void btn_cerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_cerrarActionPerformed
        this.mnuCerrarActionPerformed(null);
    }//GEN-LAST:event_btn_cerrarActionPerformed

    private void btn_borrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_borrarActionPerformed
                deleteData((Cliente)this.resultList.get(this.tabla_clientes.getSelectedRow()));
                
    }//GEN-LAST:event_btn_borrarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_borrar;
    private javax.swing.JButton btn_cerrar;
    private javax.swing.JButton btn_edit;
    private javax.swing.JButton btn_newClient;
    private javax.swing.JButton btn_save;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JMenuItem mnuCerrar;
    private javax.swing.JMenuItem mnu_newClient;
    private javax.swing.JTable tabla_clientes;
    private javax.swing.JTextField txt_apellido;
    private javax.swing.JTextField txt_cedula;
    private javax.swing.JLabel txt_lastUpdate;
    private javax.swing.JTextField txt_mail;
    private javax.swing.JTextField txt_nombre;
    // End of variables declaration//GEN-END:variables
}
